package com.xiang.publicdemo.module2.listener;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;

@WebListener
@Slf4j
public class MyHttpSessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent arg0) {
        HttpSession session = arg0.getSession();
        ServletContext context = session.getServletContext();
        if (context.getAttribute("count")==null) {
            context.setAttribute("count", 0);
        }else {
            int count = (Integer) context.getAttribute("count");
            context.setAttribute("count", count+1);
        }
        log.debug("session 创建 ... id:{}",session.getId());
    }


    public void sessionDestroyed(HttpSessionEvent arg0) {
        ServletContext context = arg0.getSession().getServletContext();
        if (context.getAttribute("count")==null) {
            context.setAttribute("count", 0);
        }else {
            int count = (Integer) context.getAttribute("count");
            if (count<1) {
                count = 1;
            }
            context.setAttribute("count", count-1);
        }
        HttpSession session = arg0.getSession();
        log.debug("session 销毁 ... id:{}",session.getId());
    }
}